<template>
  <ScrollWrapper>
    <div class="container">
      <div class="container-content">
        <!-- 页面头部 -->
        <div class="header">
          <div class="title">
            <div ref="dropdownWrapper" style="position: relative;  width: 250px;">
              <a-input-search
                  v-model="searchValue"
                  placeholder="请输入搜索内容"
                  @focus="visible=true"
                  @change="onSearchChange"
                  @click.stop
                  allowClear
              />
              <transition name="fade">
                <div
                    v-if="visible"
                    class="custom-dropdown"
                    style="position: absolute; top: 100%; left: 0; z-index: 1000; background: white; border: 1px solid #ccc; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,.15); max-height: 300px; overflow-y: auto; width: 100%;"
                    @click.stop
                >
                  <div class="search-title">筛选器</div>
                  <a-tree
                      checkable
                      :checkedKeys="checkedKeys"
                      :expandedKeys="expandedKeys"
                      :autoExpandParent="autoExpandParent"
                      :treeData="treeData"
                      @expand="onExpand"
                      @check="onCheck"
                  />
                </div>
              </transition>
            </div>
            <a-date-picker style="margin-left: 10px" v-model:value="time" placeholder="考核年月"/>
          </div>
          <div class="actions">
            <a-button class="sync-btn" @click="handleSync">清空条件</a-button>
            <a-button type="primary" class="add-btn" @click="handleAdd">筛选</a-button>
          </div>
        </div>
        <div class="checked-container" v-if="onlyLeafChecked.length">
          <div class="checked-item" v-for="item of onlyLeafChecked">
            <img src="/src/assets/img/avatar.jpg" alt="" class="avatar">
            <div class="name" :style="{backgroundColor:getRandomColor()}">Alex</div>
            <div class="close" @click="onRemove(item)">X</div>
          </div>
        </div>
        <!-- 数据表格 -->
        <div class="table-container">
          <a-table
              :columns="columns"
              :data-source="dataSource"
              :pagination="false"
              :scroll="{ x: 1200 }"
              class="department-table"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <div class="action-buttons">
                  <a-button size="small" class="detail-btn" @click="handleViewDetail(record)">
                    详情
                  </a-button>
                </div>
              </template>
            </template>
          </a-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <a-pagination
              v-model:current="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :show-size-changer="false"
              :show-quick-jumper="false"
              @change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </ScrollWrapper>
</template>

<script>
import ScrollWrapper from "@/components/ScrollWrapper/ScrollWrapper.vue";
import {message} from 'ant-design-vue';

export default {
  components: {
    ScrollWrapper,

  },
  data() {
    return {
      time: "",
      visible: false,
      searchValue: '',
      expandedKeys: [],   // 展开的节点key数组
      autoExpandParent: true,
      checkedKeys: [],    // 选中的节点key数组
      onlyLeafChecked: [],
      dataList: [],
      treeData: [
        {
          title: '市场部',
          key: '1',
          children: [
            {
              title: 'Alex',
              key: '2',
            },
            {
              title: 'Yuette',
              key: '3',
            },
          ],
        },
        {
          title: '出运中心',
          key: '4',
          children: [
            {
              title: 'Hazel',
              key: '5',
            },
          ],
        },
        {
          title: '财务',
          key: '6',
          children: [
            {
              title: 'Annie',
              key: '7',
            },
          ],
        },
      ],
      currentPage: 1,
      pageSize: 10,
      total: 40,
      columns: [
        {
          title: '隶属部门',
          dataIndex: 'department',
          key: 'department',
          align: 'center'
        },
        {
          title: '考核人',
          dataIndex: 'assessor',
          key: 'assessor',
          align: 'center'
        },
        {
          title: '考核年月',
          dataIndex: 'time',
          key: 'time',
          align: 'center'
        },
        {
          title: '岗位级别',
          dataIndex: 'level',
          key: 'level',
          align: 'center'
        },
        {
          title: '模板标识',
          dataIndex: 'temp',
          key: 'temp',
          align: 'center'
        },
        {
          title: '税前(￥)',
          dataIndex: 'all',
          key: 'all',
          align: 'center'
        },
        {
          title: '税后(￥)',
          dataIndex: 'final',
          key: 'final',
          align: 'center'
        },
        {
          title: '审核人',
          dataIndex: 'reviewer',
          key: 'reviewer',
          align: 'center'
        },
        {
          title: '公司成本',
          dataIndex: 'cost',
          key: 'cost',
          align: 'center'
        },
        {
          title: '',
          key: 'action',
          align: 'center'
        }
      ],
      dataSource: [
        {
          department: '市场部',
          assessor: '考核人',
          time: '2025-07',
          level: '初级财务专员',
          temp: 'P7',
          all: 5146,
          final: 4563,
          reviewer: "Alex",
          cost: 6200
        },
        {
          department: '市场部',
          assessor: '考核人',
          time: '2025-07',
          level: '初级财务专员',
          temp: 'P7',
          all: 5146,
          final: 4563,
          reviewer: "Alex",
          cost: 6200
        },
        {
          department: '市场部',
          assessor: '考核人',
          time: '2025-07',
          level: '初级财务专员',
          temp: 'P7',
          all: 5146,
          final: 4563,
          reviewer: "Alex",
          cost: 6200
        },
        {
          department: '市场部',
          assessor: '考核人',
          time: '2025-07',
          level: '初级财务专员',
          temp: 'P7',
          all: 5146,
          final: 4563,
          reviewer: "Alex",
          cost: 6200
        },
        {
          department: '市场部',
          assessor: '考核人',
          time: '2025-07',
          level: '初级财务专员',
          temp: 'P7',
          all: 5146,
          final: 4563,
          reviewer: "Alex",
          cost: 6200
        },
        {
          department: '市场部',
          assessor: '考核人',
          time: '2025-07',
          level: '初级财务专员',
          temp: 'P7',
          all: 5146,
          final: 4563,
          reviewer: "Alex",
          cost: 6200
        }, {
          department: '市场部',
          assessor: '考核人',
          time: '2025-07',
          level: '初级财务专员',
          temp: 'P7',
          all: 5146,
          final: 4563,
          reviewer: "Alex",
          cost: 6200
        },
        {
          department: '市场部',
          assessor: '考核人',
          time: '2025-07',
          level: '初级财务专员',
          temp: 'P7',
          all: 5146,
          final: 4563,
          reviewer: "Alex",
          cost: 6200
        },
        {
          department: '市场部',
          assessor: '考核人',
          time: '2025-07',
          level: '初级财务专员',
          temp: 'P7',
          all: 5146,
          final: 4563,
          reviewer: "Alex",
          cost: 6200
        },

      ]
    }
  },
  created() {
    this.dataList = [];
    this.generateList(this.treeData);
    this.expandedKeys = this.dataList.map(item => item.key);
  },
  mounted() {
    document.addEventListener('click', this.handleClickOutside);
  },
  beforeUnmount() {
    document.removeEventListener('click', this.handleClickOutside);
  },
  methods: {
    handleClickOutside(event) {
      // 点击事件如果不在组件内部，则关闭下拉
      if (!this.$refs.dropdownWrapper.contains(event.target)) {
        this.visible = false;
      }
    },
    generateList(data) {
      data.forEach(item => {
        this.dataList.push({key: item.key, title: item.title});
        if (item.children) {
          this.generateList(item.children);
        }
      });
    },
    getParentKey(key, tree) {
      let parentKey;
      for (let node of tree) {
        if (node.children) {
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key;
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys;
      const leafKeys = this.getLeafKeys(this.treeData);

      this.onlyLeafChecked = checkedKeys.filter(key => leafKeys.includes(key));
    },
    getLeafKeys(nodes) {
      let leafKeys = [];
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          leafKeys = leafKeys.concat(this.getLeafKeys(node.children));
        } else {
          leafKeys.push(node.key);
        }
      });
      return leafKeys;
    },

    onRemove(item) {
      console.log(item, this.checkedKeys);
      this.checkedKeys = [...this.checkedKeys.filter(k => k !== item)]

      const leafKeys = this.getLeafKeys(this.treeData);
      this.onlyLeafChecked = this.checkedKeys.filter(key => leafKeys.includes(key));
    },

    onSearchChange(e) {
      const value = e.target.value;
      this.searchValue = value;

      if (!value) {
        // 搜索框清空时，默认展开所有节点
        this.expandedKeys = this.dataList.map(item => item.key);
        this.autoExpandParent = false;
        return;
      }

      // 根据搜索值找到所有匹配的节点父节点，展开这些父节点
      const expandedKeys = this.dataList
          .map(item => {
            if (item.title.indexOf(value) > -1) {
              return this.getParentKey(item.key, this.treeData);
            }
            return null;
          })
          .filter((item, i, self) => item && self.indexOf(item) === i);

      this.expandedKeys = expandedKeys;
      this.autoExpandParent = true;
    },

    handleSync() {
      this.searchValue = ""
    },
    handleAdd() {

    },
    handleViewDetail(record) {
      message.info(`查看 ${record.departmentName} 详情`);
    },
    handleToggleStatus(record) {
      const newStatus = record.status === '正常' ? '作废' : '正常';
      record.status = newStatus;
      message.success(`${record.departmentName} 已${newStatus}`);
    },
    handlePageChange(page) {
      this.currentPage = page;
      message.info(`切换到第 ${page} 页`);
    },
    getRandomColor() {
      // 生成随机十六进制颜色
      return '#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0');
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0px 20px 24px 0;
  box-sizing: border-box;
}

.container-content {
  background-color: #fff;
  display: flex;
  margin-top: 20px;
  flex-direction: column;
  border-radius: 30px;
  flex: 1;
  padding: 24px 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-left: 24px;
    margin-top: 20px;
    display: flex;
    align-items: center;
  }

  .actions {
    display: flex;
    gap: 12px;
    margin: 0 30px;

    .sync-btn {
      color: #3a7c5a;
      font-weight: 400;
      border-radius: 6px;
      width: 110px;
      border-color: #3a7c5a;

      &:hover {
        opacity: 0.6;
      }
    }

    .add-btn {
      background-color: #3a7c5a;
      border-radius: 6px;
      width: 110px;

      &:hover {
        opacity: 0.6;
      }
    }
  }
}

.table-container {
  flex: 1;
  margin-bottom: 24px;

  :deep(.department-table) {
    .ant-table-thead > tr > th {
      background-color: #fff;
      font-weight: 500;
      color: #666;
      border-bottom: 1px solid #f0f0f0;
      padding: 16px 8px;
    }

    .ant-table-tbody > tr > td {
      padding: 16px 8px;
      border-bottom: 1px solid #f0f0f0;
      color: #333;
    }

    .ant-table-tbody > tr:hover > td {
      background-color: #f5f5f5;
    }

    .ant-table-cell:before {
      width: 0 !important;
    }

    .ant-table-thead > tr > .ant-table-cell {
      color: #d9d9d9;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;

    .detail-btn {
      background-color: #3a7c5a;
      color: #fff;
      border-radius: 4px;
      font-size: 12px;
      width: 80px;

      &:hover {
        opacity: 0.6;
      }
    }

    .enable-btn {
      background-color: #3a7c5a;
      color: #fff;
      border-radius: 4px;
      font-size: 12px;
      width: 80px;

      &:hover {
        opacity: 0.6;
      }
    }

    .disable-btn {
      background-color: #ff4d4f;
      border-color: #ff4d4f;
      color: #fff;
      border-radius: 4px;
      font-size: 12px;
      width: 80px;

      &:hover {
        background-color: #ff7875;
        border-color: #ff7875;
      }
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;

  :deep(.ant-pagination) {
    .ant-pagination-item {
      border-radius: 4px;

      &.ant-pagination-item-active {
        background-color: #3a7c5a;
        border-color: #3a7c5a;

        a {
          color: #fff;
        }
      }
    }

    .ant-pagination-prev,
    .ant-pagination-next {
      border-radius: 4px;

      &:hover {
        border-color: #3a7c5a;
        color: #3a7c5a;
      }
    }
  }
}

:deep(.ant-tag) {
  border-radius: 12px;
  padding: 2px 8px;
  font-size: 12px;

  &.ant-tag-green {
    background-color: #f6ffed;
    border-color: #b7eb8f;
    color: #52c41a;
  }

  &.ant-tag-orange {
    background-color: #fff7e6;
    border-color: #ffd591;
    color: #fa8c16;
  }
}

.search-title {
  font-size: 14px;
  color: #777;
  margin-bottom: 10px;
  margin-left: 10px;
}

.custom-dropdown {
  padding: 20px 10px;
  border-radius: 6px;
}

.checked-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 10px;
  margin-left: 24px;

  .checked-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    margin-left: -10px;

    .avatar {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      border: 1px solid #fff;
      z-index: 11;
    }

    .name {
      white-space: nowrap;
      padding: 2px 12px;
      border-radius: 10px;
      font-size: 12px;
      margin-top: -4px;
      z-index: 10;
    }

    .close {
      position: absolute;
      border-radius: 50%;
      width: 16px;
      height: 16px;
      top: -8px;
      right: 0px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: red;

      &:hover {
        opacity: 0.6;
        cursor: pointer;
      }
    }
  }
}
</style>